package com.example.service.impl;

import ch.qos.logback.classic.Logger;
import com.example.entity.*;
import com.example.ext.entity.ExtApplyRepair;
import com.example.ext.entity.ExtElevator;
import com.example.mapp.*;
import com.example.service.ApplyRepairService;
import com.example.util.PromotionUtil;
import com.example.util.ResultUtil;
import com.example.util.StringUtil;
import com.example.util.SystemPointUtil;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by douyx on 2018/03/25.
 */
@Service
public class ApplyRepairServiceImpl implements ApplyRepairService {

	private final static Logger logger = (Logger) LoggerFactory.getLogger(ApplyRepairServiceImpl.class);

	@Autowired
	private ApplyRepairMapp applyRepairMapp;

	@Autowired
	private MessageNoticeMapp messageNoticeMapp;

	@Autowired
	private ElevatorMapp elevatorMapp;

	@Autowired
	private PromotionMapp promotionMapp;

	@Autowired
	private PointFlowMapp pointFlowMapp;



	@Override
	public Map<String, Object> queryList(ExtApplyRepair extApplyRepair) {
		List<ExtApplyRepair> list = null;
		Map<String, Object> map = new HashMap<String, Object>();
		try {
//			Page<ExtApplyRepair> page = PageHelper.startPage(extApplyRepair.getCurrentPage(),
//					extApplyRepair.getPageSize());
			list = applyRepairMapp.queryList(extApplyRepair);
			map.put("list", list);
//			map.put("total", page.getTotal());
		} catch (Exception e) {
			logger.error(e.getMessage());
			return ResultUtil.returnError("查询失败" + e.getMessage(), null);
		}
		return ResultUtil.returnSuccess("查询成功", map);
	}

	@Override
	@Transactional
	public Map<String, Object> add(ApplyRepair applyRepair) {
		try {
			//查一些电梯基本信息
			ExtElevator extElevator = elevatorMapp.queryById(applyRepair.getElevatorId());

			applyRepair.setApproveStatus("0");
			applyRepair.setDealStatus("0");
			applyRepair.setUsedPartyId(extElevator.getUsedPartyId()+"");
			applyRepair.setMaintenancePartyId(extElevator.getMaintenancePartyId()+"");
			//新增报修单
			int i = applyRepairMapp.add(applyRepair);

			//开始发消息通知
			String content = applyRepair.getPartyName() +"的"+ applyRepair.getRecorderName() + "提出，外部编号"
					+ extElevator.getOutsideNum() + "的电梯有以下问题：" + applyRepair.getApplyQuestion() + "，请及时处理。";
			String noticeTime = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
			if ("2".equals(applyRepair.getApplyType())) {
				if(extElevator.getMaintenanceUserFirst()!=null){
					MessageNotice msg = new MessageNotice();
					msg.setTitle("电梯故障召修单");
					msg.setContent(content);
					msg.setReceiveUserId(String.valueOf(extElevator.getMaintenanceUserFirst()));
					msg.setIsRead("0");
					msg.setNoticeTime(noticeTime);
					msg.setReceivePartyId(String.valueOf(extElevator.getMaintenancePartyId()));
					msg.setElevatoriType("5");
					msg.setElevatoriMonId(applyRepair.getId()+"");
					messageNoticeMapp.add(msg);
				}
//				else{
//					TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//					return ResultUtil.returnError("报修失败,此电梯没有维保人员！", null);
//				}
				//先注释调，会有问题，此消息状态会改变不了，发给多人。
				if(extElevator.getMaintenanceUserSecond() != null && !extElevator.getMaintenanceUserSecond().equals(extElevator.getMaintenanceUserFirst())){
					MessageNotice msg2 = new MessageNotice();
					msg2.setTitle("电梯故障召修单");
					msg2.setContent(content);
					msg2.setReceiveUserId(String.valueOf(extElevator.getMaintenanceUserSecond()));
					msg2.setIsRead("0");
					msg2.setNoticeTime(noticeTime);
					msg2.setReceivePartyId(String.valueOf(extElevator.getMaintenancePartyId()));
					msg2.setElevatoriType("5");
					msg2.setElevatoriMonId(applyRepair.getId()+"");
					messageNoticeMapp.add(msg2);
				}

				if (extElevator.getUsedPartyId() != null) {
					addEmpiric(extElevator.getUsedPartyId(), "3", 10, "提交1份召修记录");
				}
			} else if ("1".equals(applyRepair.getApplyType())) {
				MessageNotice msg = new MessageNotice();
				msg.setTitle("电梯故障报修单");
				msg.setContent(content);
				msg.setReceiveUserId(String.valueOf(extElevator.getSafeUserId()));
				msg.setIsRead("0");
				msg.setNoticeTime(noticeTime);
				msg.setReceivePartyId(String.valueOf(extElevator.getUsedPartyId()));
				msg.setElevatoriType("5");
				msg.setElevatoriMonId(applyRepair.getId()+"");
				messageNoticeMapp.add(msg);
				
				if (extElevator.getMaintenanceUserFirst() != null) {
					addEmpiric(extElevator.getMaintenanceUserFirst(), "4", 10, "提交1份报修记录");
				}
				if (extElevator.getMaintenanceUserSecond() != null) {
					addEmpiric(extElevator.getMaintenanceUserSecond(), "4", 10, "提交1份报修记录");
				}
			}
		} catch (Exception e) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			logger.error(e.getMessage());
			return ResultUtil.returnError("提交失败" + e.getMessage(), null);
		}finally {
			if(StringUtil.isNotBlank(applyRepair.getApplyType())){
				// 2是召修申请
				if("2".equals(applyRepair.getApplyType())){
					//判断角色，是否是电梯安全管理员
					if(applyRepair.getRoleId()==5){
						// 获取缓存
						PointDefendInfoCache infoCache = new PointDefendInfoCache();
						// 获取维保人员的积分规则
						PointDefend defend = infoCache.getKeyByValue("submit_apply_for");

						// 获取用户，计算积分
						Map<String, Object> maps = pointFlowMapp.findUserInfoByUserId(Long.valueOf(applyRepair.getSysUserId()));
						long mark = (long) maps.get("mark");
						int round = (int) (mark + defend.getMark());
						// 更新用户信息总积分
						String userId = maps.get("userId").toString();
						int i1 = pointFlowMapp.updateMark(round, userId);

						String userName = maps.get("userName").toString();
						String partyName = maps.get("partyName").toString();
						SystemPointUtil.insertFlow(pointFlowMapp, i1, defend, round, userName, partyName, applyRepair.getSysUserId()+"提交一份召修申请");
					}
				}
				// 1是报修申请
				if("1".equals(applyRepair.getApplyType())){
					// 判断是否是维保用户
					if(applyRepair.getRoleId()==7){
						// 获取缓存
						PointDefendInfoCache infoCache = new PointDefendInfoCache();
						// 获取维保人员的积分规则
						PointDefend defend = infoCache.getKeyByValue("submit_repairs_application");

						// 获取用户1，计算积分
						Map<String, Object> maps = pointFlowMapp.findUserInfoByUserId(Long.valueOf(applyRepair.getSysUserId()));
						long mark = (long) maps.get("mark");
						int round = (int) (mark + defend.getMark());
						// 更新用户信息总积分
						String userId = maps.get("userId").toString();
						int i1 = pointFlowMapp.updateMark(round, userId);

						String userName = maps.get("userName").toString();
						String partyName = maps.get("partyName").toString();
						SystemPointUtil.insertFlow(pointFlowMapp, i1, defend, round, userName, partyName, applyRepair.getSysUserId()+"提交一份报修申请");
					}
				}
			}
		}
		return ResultUtil.returnSuccess("提交成功", null);
	}

	@Override
	public Map<String, Object> update(ApplyRepair applyRepair) {
		try {

			applyRepairMapp.update(applyRepair);
			if("1".equals(applyRepair.getDealStatus())){
				return ResultUtil.returnSuccess("更新成功", null);
			}
			ExtElevator extElevator = elevatorMapp.queryById(applyRepair.getElevatorId());
			//开始发消息通知
			String content="电梯故障报修单审批结果";
			String noticeTime = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
            String title1 = "";
            String content1 = "";
			String title="电梯故障报修单审批结果";
			if("2".equals(applyRepair.getApplyType())){
                /**
                 * 召修单给电梯管理员单独发送一个审批通过的消息，再给两个维保人员发个任务提示的消息
                 */
				if("1".equals(applyRepair.getApproveStatus())){
                    title1 = "电梯故障召修单审批通过";
                    content1 =  applyRepair.getRecorderName() + ",您提出的外部编号"+ extElevator.getOutsideNum() + "的电梯有以下问题：" + applyRepair.getApplyQuestion() + "，审批已经通过，维修人员正在跟进。";

					title = "电梯故障新维修任务";
					content = applyRepair.getPartyName() +"的"+ applyRepair.getRecorderName() + "提出，外部编号"
							+ extElevator.getOutsideNum() + "的电梯有以下问题：" + applyRepair.getApplyQuestion() + "，请及时维修。";
				}
				if("2".equals(applyRepair.getApproveStatus())){
                    title1 = "电梯故障召修单审批拒绝";
                    content1 =  applyRepair.getRecorderName() + ",您提出的外部编号"+ extElevator.getOutsideNum() + "的电梯有以下问题：" + applyRepair.getApplyQuestion() + "，审批审批未通过,请悉知。";
//					title = "电梯故障召修单审批拒绝";
//					content = applyRepair.getPartyName() +"的"+ applyRepair.getRecorderName() + "提出，外部编号"
//							+ extElevator.getOutsideNum() + "的电梯有以下问题：" + applyRepair.getApplyQuestion() + "，经审批未通过,请悉知。";
				}

                /**
                 * 给召修人发送审批消息
                 */
                if(extElevator.getSafeUserId() != null){
                    MessageNotice message = new MessageNotice();
                    message.setTitle(title1);
                    message.setContent(content1);
                    message.setReceiveUserId(String.valueOf(extElevator.getSafeUserId()));
                    message.setIsRead("0");
                    message.setNoticeTime(noticeTime);
                    message.setReceivePartyId(String.valueOf(extElevator.getUsedPartyId()));
                    messageNoticeMapp.add(message);
                }
				if (extElevator.getMaintenanceUserFirst() != null) {
					addEmpiric(extElevator.getMaintenanceUserFirst(), "4", 5, "确认1份召修记录");
				}
				if (extElevator.getMaintenanceUserSecond() != null) {
					addEmpiric(extElevator.getMaintenanceUserSecond(), "4", 5, "确认1份召修记录");
				}
			}else{

				if("1".equals(applyRepair.getApproveStatus())){
					title = "电梯故障报修单审批通过";
					content = applyRepair.getPartyName() +"的"+ applyRepair.getRecorderName() + "提出，外部编号"
							+  extElevator.getOutsideNum()  + "的电梯有以下问题：" + applyRepair.getApplyQuestion() + "，经审批已经通过，请及时维修。";
				}
				if("2".equals(applyRepair.getApproveStatus())){
					title = "电梯故障报修单审批拒绝";
					content = applyRepair.getPartyName() +"的"+ applyRepair.getRecorderName() + "提出，外部编号"
							+  extElevator.getOutsideNum()  + "的电梯有以下问题：" + applyRepair.getApplyQuestion() + "，经审批未通过,请悉知。";
				}
				if (extElevator.getUsedPartyId() != null) {
					addEmpiric(extElevator.getUsedPartyId(), "3", 5, "确认1份报修记录");
				}
			}
			if(extElevator.getMaintenanceUserFirst()!=null){
				MessageNotice msg = new MessageNotice();
				msg.setTitle(title);
				msg.setContent(content);
				msg.setReceiveUserId(String.valueOf(extElevator.getMaintenanceUserFirst()));
				msg.setIsRead("0");
				msg.setNoticeTime(noticeTime);
				msg.setReceivePartyId(String.valueOf(extElevator.getMaintenancePartyId()));

				messageNoticeMapp.add(msg);
			}
			//先注释调，会有问题，此消息状态会改变不了，发给多人。
			if(extElevator.getMaintenanceUserSecond() != null && !extElevator.getMaintenanceUserSecond().equals(extElevator.getMaintenanceUserFirst())){
				MessageNotice msg2 = new MessageNotice();
				msg2.setTitle(title);
				msg2.setContent(content);
				msg2.setReceiveUserId(String.valueOf(extElevator.getMaintenanceUserSecond()));
				msg2.setIsRead("0");
				msg2.setNoticeTime(noticeTime);
				msg2.setReceivePartyId(String.valueOf(extElevator.getMaintenancePartyId()));

				messageNoticeMapp.add(msg2);
			}


		} catch (Exception e) {
			logger.error(e.getMessage());
			return ResultUtil.returnError("更新失败" + e.getMessage(), null);
		}
		return ResultUtil.returnSuccess("更新成功", null);
	}

	private void addEmpiric(Long userId, String type, Integer empiricValue, String content) throws Exception{
		/**
		 * 积分调整了，原先代码注释掉
		 */


		/*Map<String, Object> map = new HashMap<>();
		map.put("type", type);
		map.put("userId", userId);
		Promotion promotion = promotionMapp.findById(map);
		if (null != promotion && promotion.getId() != null) {
			promotion = PromotionUtil.calc(promotion, type, empiricValue, false);
			promotionMapp.update(promotion);
		} else {
			promotion = new Promotion();
			promotion.setType(type);
			promotion.setUserId(userId.toString());
			promotion = PromotionUtil.calc(promotion, type, empiricValue, true);
			promotionMapp.insert(promotion);
		}
		PromotionRecord promotionRecord = new PromotionRecord();
		promotionRecord.setUserId(promotion.getUserId());
		promotionRecord.setType(promotion.getType());
		promotionRecord.setEmpiricItem(content);
		promotionRecord.setAddedTime(PromotionUtil.getTime());
		promotionRecord.setEmpiricValue(empiricValue);
		promotionMapp.insertRecord(promotionRecord);*/
	}
	
	@Override
	public Map<String, Object> queryById(String id) {
		try {
			ExtApplyRepair extApplyRepair = applyRepairMapp.queryById(id);
			return ResultUtil.returnSuccess("提交成功", extApplyRepair);
		} catch (Exception e) {
			logger.error(e.getMessage());
			return ResultUtil.returnError("提交失败" + e.getMessage(), null);
		}
	}
}
